package Servlets;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import Server.ServerProtocol;


public class UploadFile extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	private static final String NEW_LINE=System.getProperty("line.separator").toString();

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
	{
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out=response.getWriter();
		System.out.println("Check Login");

		
		String folderID=request.getSession().getAttribute("FolderID").toString();
		System.out.println("folder id is "+folderID);
		String userName=request.getSession().getAttribute("Login").toString();
		System.out.println("user name is "+userName);
		DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();

		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		uploadHandler.setHeaderEncoding("UTF-8");

		out.println("<html>");
		out.println("<head>");
		out.println("<title> CleverDrop Box </title>");
		

		try {

			//Parse the request    
			List<FileItem> items = uploadHandler.parseRequest(request);
			String name =null;
			byte[] data =null;
			long checksum;

			Iterator itr = items.iterator();
			while(itr.hasNext()) {
				FileItem item = (FileItem) itr.next();

				if (!item.isFormField())
				{
					name = item.getName();
					System.out.println("&&& = "+name);
					//if there is really a file (the field is not empty)
					if (!name.equals(""))
					{
						//get the file and add it
						data = item.get();
						ServerProtocol.getInstance().addFileFromServer(data, name, folderID, userName);
					}

				}
				out.println("<meta HTTP-EQUIV='REFRESH' content='0; url=afterUpload.jsp'>");
				out.println("</head>");
				out.println("<body>");
				out.println("</body>");
				out.println("</html>");

				out.close();
			}
		}
		catch(Exception e){

		}
	}
}
